import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserInput } from 'src/graphql';
import { Repository } from 'typeorm';
import { User } from '../../entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  async findAll(findOption={}): Promise<User[]> {
    const users=await this.usersRepository.find(findOption);
    return users;
  }

  async findOne(id: number): Promise<User> {
    const res=await this.usersRepository.findOne(id);
    return res;
  }

  async removeOne(id: number): Promise<User> {
    const u=await this.findOne(id);
    const res=await this.usersRepository.delete(id);
    return res.affected===1?u:null;
  }

  async addOne(user: User): Promise<User> {
    const u=Object.assign(new User(),user);
    u.register_time=new Date();
    const res=await this.usersRepository.insert(u);
    return this.findOne(res.identifiers[0].id);
  }

  async modifyOne(id: number,user: User): Promise<User> {
    const u=Object.assign(new User(),user);
    const res=await this.usersRepository.update(id,u);
    return await this.findOne(id);
  }
  
  async count(option={}): Promise<number> {
    return await this.usersRepository.count(option);
  }

  async getPagination(page={},sort={},where={}){
    const p=Object.assign({
      size:10,
      current:0,
      total:0,
    },page);
    const users=await this.findAll({
      order:sort,
      take:p.size,
      skip:p.current,
      where:where
    });
    const total = await this.count(where);
    p.total=total;
    return {
      page:p,
      users:users,
    }
  }
}
